﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Configuration;
using System.ComponentModel;

namespace RRD2.Controler
{
    public class Messanger
    {
        public static void SendMail(Model.Statement _statement)
        {
            try
            {
                MailMessage message = new MailMessage(
                    ConfigurationManager.AppSettings["Mailsender"],
                    ConfigurationManager.AppSettings["AlertMail"],
                    _statement.Type.ToString(),
                    _statement.Value);
                
                SmtpClient mailer = new SmtpClient();
                mailer.Host = ConfigurationManager.AppSettings["MailHost"];
                mailer.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailSender"], ConfigurationManager.AppSettings["MailSenderPasswd"]);
                mailer.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
                string userState = "test message1";
                mailer.SendAsync(message, userState);
            }
            catch (Exception ex)
            {
                DAL.Logger.WriteException(ex);
            }
        }

        private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                DAL.Logger logger = new DAL.Logger();
                String token = (string)e.UserState;
                Model.Statement statement = new Model.Statement();

                
                if (e.Error != null)
                {
                    //Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
                    statement.Value = e.Error.ToString();
                    statement.Type = Model.StatementType.Error;
                }
                else
                {
                    statement.Value = ConfigurationManager.AppSettings["MailConfirmSent"];
                    statement.Type = Model.StatementType.Message;
                }
                logger.WriteLog(statement, "mail");
            }
            catch (Exception ex)
            {
                DAL.Logger.WriteException(ex);
            }
        }

        public static void PlaySound()
        {
            try
            {
                System.Media.SoundPlayer sp = new System.Media.SoundPlayer(ConfigurationManager.AppSettings["Sound"]);
                sp.Play();
            }
            catch (Exception ex)
            {
                DAL.Logger.WriteException(ex);
            }

        }
    }
}
